//
//  WWDViewController.m
//  MyBleTest2
//
//  Created by maginawin on 14-8-11.
//  Copyright (c) 2014年 mycj.wwd. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "LightingViewController.h"
#import "NavigationController.h"
@interface ViewController ()
{
    int count;
    
}
- (NSString*)hexadecimalString:(NSData*)data;
- (NSData*)dataWithHexstring:(NSString*)hexstring;
- (void)writeToPeripheral:(NSString*)data;
@property(strong,nonatomic) IBOutlet UIActivityIndicatorView *searching;
@property (strong, nonatomic) NSMutableString* values;
@property (strong, nonatomic) NSMutableString* valuesTest;
@property (nonatomic) NSUInteger intTest;

@end

@implementation ViewController

#pragma mark -8
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _searching.hidden = YES;
    
    count = 0;
    
    self.myCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
    
    self.values = [NSMutableString stringWithString:@""];
    
    _myPeripherals = [NSMutableArray array];

    _tableView.dataSource = self;
    
    _tableView.delegate = self;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    if(count != 0) {
        [self disconnect];
        NSLog(@"5秒之后重新刷新");
        double delayInSeconds = 4.0;
        _searching.hidden = NO;
        [_searching startAnimating];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds* NSEC_PER_SEC));
        
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            [self conn];
            
        });
        NSLog(@"搜索成功....");
        
    }
    count ++;
    
}
- (void)conn {
    [self.myCentralManager stopScan];
    if(_myPeripherals != nil){
        _myPeripherals = nil;
        _myPeripherals = [NSMutableArray array];
        [_tableView reloadData];
    }
    _tableView.hidden = NO;
    
    [self scanClick];
    
}
- (void)disconnect {
    
    NSLog(@"断开现在的链接");
    
    [self.myCentralManager cancelPeripheralConnection:self.myPeripheral];
}
- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}

#pragma mark -
- (void)scanClick {
    
    NSLog(@"正在扫描外设...");
    
    [self.myCentralManager scanForPeripheralsWithServices:nil options:nil];
    
    if(_myPeripheral != nil){
        
        [_myCentralManager cancelPeripheralConnection:_myPeripheral];
        
    }
    
    double delayInSeconds = 5.0;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds* NSEC_PER_SEC));
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        [self.myCentralManager stopScan];
        
        NSLog(@"扫描超时,停止扫描!");
        
    });
}

//连接
- (void)connectClick {
    
    [self.myCentralManager connectPeripheral:self.myPeripheral options:nil];
    
}

//开始查看服务, 蓝牙开启
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
            
        case CBCentralManagerStatePoweredOn:
            [self conn];
            break;
            
        default:
            break;
            
    }
}

//查到外设后的方法,peripherals
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    for(CBPeripheral *p in self.myPeripherals) {
        if([p.identifier isEqual:peripheral.identifier]) {
            return;
        }
    }
    NSLog(@"已发现 peripheral: %@ rssi: %@ advertisementData: %@", peripheral, RSSI, advertisementData);
        [_myPeripherals addObject:peripheral];
    
    //NSInteger count = [_myPeripherals count];
    _searching.hidden = YES;
    [_tableView reloadData];
    [_searching stopAnimating];
}

//连接外设成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"成功连接 peripheral: %@",peripheral);
    [self.myPeripheral setDelegate:self];
    [self.myPeripheral discoverServices:nil];
    
    NSLog(@"扫描服务...");
    
}

//掉线时调用
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    self.isConnected = NO;
    NSLog(@"periheral has disconnect");
}

//连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    NSLog(@"%@", error);
    
    
}

//已发现服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    
    NSLog(@"发现服务!");
    
    int i = 0;
    
    for(CBService* s in peripheral.services) {
        
        [self.nServices addObject:s];
        
    }
    
    for(CBService* s in peripheral.services) {
        
        NSLog(@"%d :服务 UUID: %@(%@)", i, s.UUID.data, s.UUID);
        
        i++;
        
        [peripheral discoverCharacteristics:nil forService:s];
        
        NSLog(@"扫描Characteristics...");
    }
}

#pragma mark - about uuid
//已发现characteristcs
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    NSString *readwrite = @"FFF1";
    for(CBCharacteristic* c in service.characteristics) {
        
        NSLog(@"特征 UUID: %@ (%@)", c.UUID.data, c.UUID);
        if([c.UUID isEqual:[CBUUID UUIDWithString:readwrite]]) {
            self.writeCharacteristic = c;
            self.readCharacteristic = c;
            NSLog(@"发现uuid为 %@ 的服务\n",readwrite);
            
            
        }
    }
}


//获取外设发来的数据,不论是read和notify,获取数据都从这个方法中读取
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    [peripheral readRSSI];
    
    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]){
        
        NSData* data = characteristic.value;
        
        NSString* value = [self hexadecimalString:data];
        
        NSLog(@"characteristic : %@, data : %@, value : %@", characteristic, data, value);
        
        [self.values appendString:[NSString stringWithFormat:@"%@\n",value]];
    }
}


//中心读取外设实时数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    if(error){
        NSLog(@"Error changing notification state: %@", error.localizedDescription);
    }
    
    //Notification has started
    if(characteristic.isNotifying) {
        
        [peripheral readValueForCharacteristic:characteristic];
        
    }
    else {
        
        NSLog(@"Notification stopped on %@. Disconnting", characteristic);
        
        [self.myCentralManager cancelPeripheralConnection:self.myPeripheral];
        
    }
}


//向peripheral中写入数据
- (void)writeToPeripheral:(NSString *)data{
    if(!_writeCharacteristic) {
        
        NSLog(@"writeCharacteristic is nil!");
        
        return;
    }
    NSData* value = [self dataWithHexstring:data];
    [_myPeripheral writeValue:value forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

//向peripheral中写入数据后的回调函数
- (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSLog(@"write value success : %@", characteristic);
}


//将传入的NSData类型转换成NSString并返回
- (NSString*)hexadecimalString:(NSData *)data{
    NSString* result;
    const unsigned char* dataBuffer = (const unsigned char*)[data bytes];
    if(!dataBuffer){
        return nil;
    }
    NSUInteger dataLength = [data length];
    NSMutableString* hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    for(int i = 0; i < dataLength; i++){
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
    }
    result = [NSString stringWithString:hexString];
    return result;
}

//将传入的NSString类型转换成NSData并返回
- (NSData*)dataWithHexstring:(NSString *)hexstring{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for(idx = 0; idx + 2 <= hexstring.length; idx += 2){
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [hexstring substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}


//连接设备[connect]
- (IBAction)connDevice:(id)sender{
    [self conn];
}

#pragma mark - TableView methods
//tableview的方法,返回section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//tableview的方法,返回rows(行数)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _myPeripherals.count;
}

//tableview的方法,返回cell的view
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //为表格定义一个静态字符串作为标识符
    static NSString* cellId = @"cellId";
    //从IndexPath中取当前行的行号
    NSUInteger rowNo = indexPath.row;
    
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    UILabel* labelName = (UILabel*)[cell viewWithTag:1];
    UILabel* labelUUID = (UILabel*)[cell viewWithTag:2];
    labelName.text = [[_myPeripherals objectAtIndex:rowNo] name];
    NSString* uuid = [NSString stringWithFormat:@"%@", [[_myPeripherals objectAtIndex:rowNo] identifier]];
    uuid = [uuid substringFromIndex:[uuid length] - 13];
    NSLog(@"%@", uuid);
    labelUUID.text = uuid;
    
    return cell;
}

//tableview的方法,点击行时触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSUInteger rowNo = indexPath.row;
 
    _myPeripheral = [_myPeripherals objectAtIndex:rowNo];
    
    [self connectClick];
    
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    NavigationController *navigationVC = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Navigation"];
    navigationVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    navigationVC.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:navigationVC animated:YES completion:nil];
    
}
- (IBAction)exitHere:(UIStoryboardSegue *)sender {
    count --;
    NSLog(@"back successed");
}
- (void)turnOn {
    [self writeToPeripheral:@"00"];
}
- (void)turnOff {
    [self writeToPeripheral:@"01"];
}

- (void)level_1 {
    NSLog(@"hello world");
    [self writeToPeripheral:@"04"];
}
- (void)level_2 {
    [self writeToPeripheral:@"03"];
}
- (void)level_3 {
    [self writeToPeripheral:@"02"];
}
- (void)color_1 {
    [self writeToPeripheral:@"07"];
}
- (void)color_2 {
    [self writeToPeripheral:@"09"];
}
- (void)color_3 {
    [self writeToPeripheral:@"0a"];
}
- (void)color_4 {
    [self writeToPeripheral:@"08"];
}
- (void)model_1 {
    [self writeToPeripheral:@"0c"];
}
- (void)model_2 {
    [self writeToPeripheral:@"0b"];
}
- (void)model_3 {
    [self writeToPeripheral:@"0d"];
}
- (void)model_4 {
    [self writeToPeripheral:@"06"];
}
@end
